package service.wechatlab.impl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import dao.wechatlab.LabelSystemDao;
import dao.wechatlab.WechatDao;
import pojo.ResCode;
import pojo.jane.AuthorityBean;
import pojo.jane.KeyWordsBean;
import pojo.jane.OperationBean;
import pojo.jane.StudentBean;
import pojo.weichatlab.Label;
import pojo.weichatlab.Wechat;
import pojo.weichatlab.WechatClassMap;
import service.wechatlab.LableSystemService;

@Service
public class LableSystemServiceImpl implements LableSystemService {

	@Autowired
	LabelSystemDao sd;
	@Autowired
	WechatDao wd;

	@Override
	public int addUserService(StudentBean st)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		// TODO Auto-generated method stub
		st.setTime(new Date());
		st.setPassword(EncoderByMd5(st.getPassword()));
		st.setAuthgroup(3);
		
		sd.insertStudent(st);

		return st.getId();
	}

	// MD5加密
	public String EncoderByMd5(String str)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		// 确定计算方法
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		String newstr = Base64.encodeBase64String(md5.digest(str.getBytes("utf-8")));
		return newstr;
	}

	@Override
	public List<StudentBean> selectStudent(String userid) {
		// TODO Auto-generated method stub
		return sd.selectStudent(userid);
	}

	@Override
	public String getSimilar() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Wechat> getText(HttpServletRequest request) {
		// TODO Auto-generated method stub
		String wechatid ;
		if(request.getParameter("wechatid") != null){
			wechatid = request.getParameter("wechatid");
		}else
			wechatid = new Random().nextInt(2000)+"";
		List<Wechat> list = wd.selectWechatById(wechatid);
		return list;
	}

	@Override
	public String setAvailableLable(Label label) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ResCode updateTextLable(HttpServletRequest request) {
		// int wechatid, int classid, Date update_time, String ip,
		// String user, String keywords, float cF
		String id = request.getParameter("id");
		HttpSession session = request.getSession();
		String user = (String) session.getAttribute("userid");
		String ip = getIpAddress(request);
		String keywords = request.getParameter("keywords");
		String labels[] = request.getParameterValues("labels");
		Float confidence = Float.parseFloat(request.getParameter("confidence"));

		
		if (id == null || labels == null) {
			return new ResCode(400, "ParamsNULL");
		}

		// 判断微信id是否合法
		List<Wechat> wtlist = wd.selectWechatById(id);
		if (wtlist.size() <= 0 || wtlist == null) {
			return new ResCode(400, "WechatIdIllegal");
		}
		Wechat wt = wtlist.get(0);
		// 判断keywords是否合法
		String[] keywordlist = keywords.split(" ");
		for (String kw : keywordlist) {
			if (!wt.getContent().contains(kw)) {
				return new ResCode(400, "KeyWordsIllegal");
			}
		}
		
		if(confidence < 0 || confidence > 1){
			return new ResCode(400, "confidence Illegal");
		}

		int iid = Integer.parseInt(id);
		List<WechatClassMap> wml = new ArrayList<WechatClassMap>();
		for (String label : labels) {
			// 判断labelid是否存在,确信度是否合法
			if (wd.selectLabelById(label) != null) {
				List<Integer> temp = wd.selectExistMaxTimes(label,iid);
				if(temp.size() > 0 && temp.get(0) != null){
				     wml.add(new WechatClassMap(iid, Integer.parseInt(label),
						new Date(), ip, user, confidence, temp.get(0)+1));
				}else {
					wml.add(new WechatClassMap(iid, Integer.parseInt(label),
						new Date(), ip, user, confidence, 1));
				}
			} else {
				return new ResCode(400, "labelId Illegal");
			}
		}
		

		// 确保参数全部合法后将label和keywords插入数据库
		KeyWordsBean kw = new KeyWordsBean(iid, new Date(), keywords, ip, user);
		sd.addKeyWords(kw);
		for (WechatClassMap wcm : wml) {
			wd.addWechatClassMap(wcm);
		}

		return new ResCode(200, "success");

	}

	public String getIpAddress(HttpServletRequest request) {
		return request.getRemoteAddr();
	}

	@Override
	public List<Integer> selectAuthgroupid(int authgroup) {
		// TODO Auto-generated method stub
		List<Integer> authid = new ArrayList<Integer>();
		List<AuthorityBean> authidlist = sd.selectAuthid(authgroup);

		for (AuthorityBean al : authidlist) {
			authid.add(al.getAuthid());
		}
		return authid;

	}

	@Override
	public List<String> selectOperation(int authid) {
		// TODO Auto-generated method stub
		List<OperationBean> operationlist = sd.selectOperation(authid);
		List<String> opl = new ArrayList<String>();
		for (OperationBean ol : operationlist) {
			opl.add(ol.getOperation());
		}

		return opl;
	}

	@Override
	public Set<String> authInfoMap(String userid) {
		// TODO Auto-generated method stub
		int authgroup = selectStudent(userid).get(0).getAuthgroup();
		List<Integer> authid = selectAuthgroupid(authgroup);
		Set<String> authlist = new HashSet<String>();
		for (Integer al : authid) {
			List<String> list = selectOperation(al);
			authlist.add(list.get(0));
		}

		return authlist;
	}

	public boolean isLegal(String userid) {
		List<StudentBean> st = sd.selectStudent(userid);
		if (st.size() != 0) {
			return false;
		} else
			return true;
	}

	@Override
	public boolean isExistUser(StudentBean st)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		// TODO Auto-generated method stub
		List<StudentBean> stlist = sd.selectStudent(st.getUserid());
		String password = EncoderByMd5(st.getPassword());
		for (StudentBean sl : stlist) {
			if (sl.getPassword().equals(password)) {
				return true;
			}
		}
		return false;
	}


}
